package com.demo.crm.springboot3security.controller;

import java.util.List;
import java.util.Optional;
import java.util.Set;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.demo.crm.springboot3security.entity.Role;
import com.demo.crm.springboot3security.service.RoleService;

import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/api/roles")
@RequiredArgsConstructor
public class RoleController {

    private final RoleService roleService;

    @GetMapping
    public ResponseEntity<List<Role>> getAllRoles() {
        return ResponseEntity.ok(roleService.findAll());
    }

    @GetMapping("/{id}")
    public ResponseEntity<Role> getRole(@PathVariable Long id) {
        return Optional.ofNullable(roleService.findById(id))
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<Role> createRole(@RequestBody CreateRoleRequest request) {
        Role role = new Role();
        role.setName(request.name());
        return ResponseEntity.ok(roleService.save(role));
    }

    @PutMapping("/{id}")
    public ResponseEntity<Role> updateRole(@PathVariable Long id, @RequestBody UpdateRoleRequest request) {
        return Optional.ofNullable(roleService.findById(id))
                .map(role -> {
                    role.setName(request.name());
                    return ResponseEntity.ok(roleService.save(role));
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteRole(@PathVariable Long id) {
        if (!Optional.ofNullable(roleService.findById(id)).isPresent()) {
            return ResponseEntity.notFound().build();
        }
        roleService.delete(id);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/{id}/permissions")
    public ResponseEntity<Void> assignPermissions(@PathVariable Long id, @RequestBody AssignPermissionsRequest request) {
        roleService.assignPermissions(id, request.permissionIds());
        return ResponseEntity.ok().build();
    }
}

record CreateRoleRequest(String name) {}
record UpdateRoleRequest(String name) {}
record AssignPermissionsRequest(Set<Long> permissionIds) {} 